package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.CheckJoinUsAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.TopCompanyEntity;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.widget.popupwind.InputTenantPassWordPopupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CheckJoinUsActivity extends BaseActivity {
    @BindView(R.id.rv_organization)
    RecyclerView rvOrganization;
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.ll_add)
    LinearLayout llDdd;
    @BindView(R.id.edt_input_search)
    EditText edtInputSearch;
    @BindView(R.id.tv_null)
    TextView tv_null;
    private CheckJoinUsAdapter checkJoinUsAdapter;
    private int changeBranch;
    private String edtString = "";
    private boolean softKeyBoard = false;//是否展示软键盘
    private InputTenantPassWordPopupWindow popupWindow;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_join_us;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        topTitle.setText("选择加入组织");
        changeBranch = getIntent().getIntExtra("changeBranch", 0);
        softKeyBoard = getIntent().getBooleanExtra("isShowSoftKeyboard", false);
        if (softKeyBoard) {
            CommonUtil.showKeyboard(edtInputSearch);
        }
        topBtnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        edtInputSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//修改回车键功能
                    //代码
                    edtString = v.getText().toString().trim();
                    initData();
                }
                return false;
            }
        });
        llDdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CheckJoinUsActivity.this, CreateLevel1OrganizationsActivity.class));
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvOrganization.setLayoutManager(layoutManager);
        checkJoinUsAdapter = new CheckJoinUsAdapter(this);
        rvOrganization.setAdapter(checkJoinUsAdapter);

        checkJoinUsAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (checkJoinUsAdapter.getData().get(position).passwordStatus) {
                    popupWindow = InputTenantPassWordPopupWindow.getInstance(CheckJoinUsActivity.this,
                            new InputTenantPassWordPopupWindow.InputContent() {
                                @Override
                                public void inputContent(String password) {
                                    verifyPassword(checkJoinUsAdapter.getData().get(position).id, password);
                                }
                            });
                    popupWindow.show();
                } else {
                    jumpToCheckTeamActivity(checkJoinUsAdapter.getData().get(position).id);
                }
            }
        });

    }

    private void jumpToCheckTeamActivity(String companyId) {
        Intent intent = new Intent(CheckJoinUsActivity.this, CheckTeamActivity.class);
        if (changeBranch == 1) {
            intent.putExtra("type", 1);
        }
        intent.putExtra("companyId", companyId);
        startActivity(intent);
    }

    /**
     * 验证密码是否正确
     *
     * @param companyId
     * @param password
     */
    private void verifyPassword(String companyId, String password) {
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("companyId", companyId);
            object.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new CompanyAPI().postVerifyPassword(object.toString(), new BaseResultCallback<BaseResponseEntity>() {
            @Override
            public void onResponse(BaseResponseEntity response) {
                dismissDialog();
                if (response != null && response.getCode() == 0) {
                    jumpToCheckTeamActivity(companyId);
                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        String string = "?tenantName=%s";
        showDialog();
        new UserAPI().getTopCompany(String.format(string, edtString), new BaseResultCallback<TopCompanyEntity>() {
            @Override
            public void onResponse(TopCompanyEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response.data != null && response.data.size() > 0) {
                        checkJoinUsAdapter.setNewInstance(response.data);
                        checkJoinUsAdapter.notifyDataSetChanged();

                        tv_null.setVisibility(View.GONE);
                        rvOrganization.setVisibility(View.VISIBLE);
                    } else {
                        tv_null.setVisibility(View.VISIBLE);
                        rvOrganization.setVisibility(View.GONE);
                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }

            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
        switch (event.getMsg()) {
            case 4:
                finish();
                break;
            default:
                break;
        }
    }
}